// pages/order/order.js
import showValidateModal from "../../utils/showValidateModal";
import utils from "../../utils/util";
const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  handleIndex(data) {
    this.setData({
      currentTab: data.detail,
    });
  },
  /* 复制微信 */
  copyWX() {
    wx.setClipboardData({
      data: "13251639603",
    });
  },
  data: {
    order: {}, //订单信息
    acceptMan: {}, //接单人
    showAcceptButton: true, //接单按钮是否显示
    showDetail: false, //查看订单详细信息开关
    completeID: "",
    isCompleted: true, //完成订单的开关
  },
  HelpUpdate() {
    wx.showModal({
      title: "确定当前订单已完成吗？",
      cancelColor: "#FA5151",
      confirmColor: "#07C160",
      success: (res) => {
        if (res.confirm) {
          const id = this.data.completeID;
          // console.log(id);
          //判断当前用户是否已申请接单权限
          if (!app.globalData.userInfo.canReceive) {
            wx.showToast({ title: "您尚未开通接单权限", icon: "error" });
            return false;
          }
          wx.request({
            url: `${app.globalData.server}/updateOrder`,
            method: "POST",
            data: {
              id,
              acceptMan: app.globalData.userInfo.openid,
              acceptTime: utils.formatTime(new Date()),
              completed: "已完成",
              status: "已帮助",
              isCompleted: false,
            },
            success: (res) => {
              wx.request({
                url: `${app.globalData.server}/findCompleted`,
                data: {
                  id,
                },
                success: (res) => {
                  this.setData({
                    isCompleted: res.data,
                  });
                },
              });
              setTimeout(() => {
                wx.switchTab({
                  url: "/pages/order/order",
                });
              }, 1000);
            },
          });
        } else if (res.cancel) {
          console.log("用户点击取消");
        }
      },
    });
  },
  //点击接单
  async acceptOrder(e) {
    const that = this;
    const { id } = e.currentTarget.dataset; //判断用户是否登录
    const r = await showValidateModal.cklogin(app.globalData.userInfo);
    if (!r) {
      return false;
    }
    // 判断用户是否绑定手机号
    if (wx.getStorageSync("userInfo").phone === "") {
      wx.showToast({
        title: "请先绑定手机号",
        icon: "error",
        success() {
          setTimeout(() => {
            wx.navigateTo({
              url: "/pages/user/personInfo/personInfo",
            });
          }, 500);
        },
      });
      return;
    }
    //判断当前用户是否已申请接单权限
    if (!app.globalData.userInfo.canReceive) {
      wx.showToast({ title: "您尚未开通接单权限", icon: "error" });
      return false;
    }
    wx.showModal({
      title: "接单确认",
      content: "您确认要接此订单么？",
      showCancel: true,
      success: (res) => {
        if (res.confirm) {
          wx.request({
            url: `${app.globalData.server}/updateOrder`,
            method: "POST",
            data: {
              id,
              acceptMan: app.globalData.userInfo.openid,
              acceptTime: utils.formatTime(new Date()),
              status: "已帮助",
              completed: "未完成",
              isCompleted: true,
            },
            success: (res) => {
              that.onLoad({ id });
            },
          });
        }
      },
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    wx.showLoading(); //获取订单id
    const { id } = options;
    if (id) {
      //读取订单信息
      this.getOrderDetail(id);
      this.setData({
        completeID: id,
      });
      wx.request({
        url: `${app.globalData.server}/findCompleted`,
        data: {
          id,
        },
        success: (res) => {
          this.setData({
            isCompleted: res.data,
          });
        },
      });
    }
  },
  // 下载附件
  downloadFile(e) {
    //读取接单人
    const { status, acceptMan } = this.data.order;
    if (!acceptMan || status === "待帮助") {
      wx.showToast({ title: "接单后才可查看！", icon: "none", duration: 2000 });
    } else {
      const _openid = app.globalData.userInfo.openid;
      if (_openid == acceptMan) {
        this.setData({ showDetail: !this.data.showDetail });
        wx.downloadFile({
          url: e.currentTarget.dataset.file.filePath[0],
          success(res) {
            wx.openDocument({
              filePath: res.tempFilePath,
              showMenu: true,
              success: function (res) {
                console.log("打开文档成功");
              },
            });
          },
        });
      } else {
        wx.showToast({
          title: "只有接单用户才可查看",
          icon: "none",
          duration: 2000,
        });
      }
    }
  },
  //读取订单信息
  getOrderDetail(id) {
    wx.request({
      url: `${app.globalData.server}/orderDetail`,
      data: { id },
      success: (res) => {
        //console.log(res)
        if (res.data.status === "success") {
          const item = res.data.result[0]; //读取接单人信息
          // console.log(item);
          var {
            _id,
            acceptMan,
            acceptManInfo,
            publicTime,
            acceptTime,
            completed,
            isCompleted,
            status,
          } = item;
          if (acceptMan) {
            this.setData({ acceptMan: acceptManInfo[0] });
          } //格式化 接单内容信息
          switch (item.orderType) {
            case "快递代取":
              var {
                _id,
                orderType,
                startAddress,
                endAddress,
                payMoney,
                publicTime,
                status,
                userInfo,
                completed,
                isCompleted,
                acceptMan,
              } = item;
              var content = `快件大小：${item.info.expressType}--快递数量： ${item.info.expressNum}--备注：${item.info.mark}--期望送达： ${item.info.arriveTime}--${item.info.genderLimit}`;
              var newItem = {
                _id,
                orderType,
                startAddress,
                endAddress,
                payMoney,
                completed,
                isCompleted,
                publicTime,
                status,
                expressInfo: item.info.expressInfo,
                img: item.info.img,
                userInfo,
                content,
                acceptMan,
              };
              break;
            case "打印服务":
              var {
                _id,
                orderType,
                endAddress,
                payMoney,
                publicTime,
                status,
                completed,
                isCompleted,
                userInfo,
                acceptMan,
              } = item;
              var content = `页数：${item.info.pageNum}--备注：${item.info.mark}- -${item.info.colorPrint}--${item.info.doublePrint}`;
              var newItem = {
                _id,
                orderType,
                endAddress,
                payMoney,
                publicTime,
                status,
                content,
                userInfo,
                completed,
                isCompleted,
                acceptMan,
                filePath: item.info.filePath,
              };
              break;
            case "校园跑腿":
              var {
                _id,
                orderType,
                startAddress,
                endAddress,
                completed,
                isCompleted,
                payMoney,
                publicTime,
                status,
                userInfo,
                acceptMan,
              } = item;
              var content = item.info.content;
              var newItem = {
                _id,
                orderType,
                startAddress,
                endAddress,
                payMoney,
                publicTime,
                status,
                completed,
                isCompleted,
                content,
                userInfo,
                acceptMan,
              };
              break;
            case "快递代寄":
              var {
                _id,
                orderType,
                startAddress,
                endAddress,
                payMoney,
                publicTime,
                status,
                userInfo,
                completed,
                isCompleted,
                acceptMan,
              } = item;
              var content = `${item.info.expressInfo}--备注：${item.info.mark}`;
              var newItem = {
                _id,
                orderType,
                startAddress,
                endAddress,
                payMoney,
                publicTime,
                status,
                userInfo,
                content,
                completed,
                isCompleted,
                acceptMan,
                infoImage: item.info.img,
              };
              break;
            case "租借服务":
              var {
                _id,
                orderType,
                startAddress,
                endAddress,
                payMoney,
                publicTime,
                status,
                userInfo,
                completed,
                isCompleted,
                acceptMan,
              } = item;
              var content = `${item.info.content}--租借时长： ${item.info.rentDuration}--预计交货时间：${item.info.deliveryTime}`;
              var newItem = {
                _id,
                orderType,
                startAddress,
                endAddress,
                payMoney,
                publicTime,
                completed,
                isCompleted,
                status,
                userInfo,
                content,
                acceptMan,
              };
              break;
            case "游戏陪玩":
              var {
                _id,
                orderType,
                payMoney,
                publicTime,
                status,
                completed,
                isCompleted,
                userInfo,
                acceptMan,
              } = item;
              var content = `游戏平台：${item.info.platform}--游戏时间或盘数： ${item.info.playDuration}--备注：${item.info.mark}--游戏ID：${item.info.gameID}`;
              var newItem = {
                _id,
                orderType,
                payMoney,
                publicTime,
                completed,
                isCompleted,
                status,
                userInfo,
                content,
                acceptMan,
              };
              break;
            case "代扔垃圾":
              var {
                _id,
                orderType,
                startAddress,
                endAddress,
                payMoney,
                publicTime,
                completed,
                isCompleted,
                status,
                userInfo,
                acceptMan,
                info,
              } = item;
              var content = `垃圾大小：${item.info.rubbishType}--垃圾数量： ${item.info.rubbishNum}--备注：${item.info.mark}`;
              var newItem = {
                _id,
                orderType,
                startAddress,
                endAddress,
                payMoney,
                publicTime,
                completed,
                isCompleted,
                status,
                userInfo,
                content,
                acceptMan,
                info,
              };
              break;
            case "代替服务":
              var {
                _id,
                orderType,
                startAddress,
                endAddress,
                payMoney,
                publicTime,
                status,
                completed,
                isCompleted,
                userInfo,
                acceptMan,
              } = item;
              var content = item.info.content;
              var newItem = {
                _id,
                orderType,
                startAddress,
                endAddress,
                payMoney,
                publicTime,
                completed,
                isCompleted,
                status,
                content,
                userInfo,
                acceptMan,
              };
              break;
            case "其他帮助":
              var {
                _id,
                orderType,
                startAddress,
                endAddress,
                completed,
                isCompleted,
                payMoney,
                publicTime,
                status,
                userInfo,
                acceptMan,
              } = item;
              var content = item.info.content;
              var newItem = {
                _id,
                orderType,
                startAddress,
                endAddress,
                payMoney,
                publicTime,
                completed,
                isCompleted,
                status,
                content,
                userInfo,
                acceptMan,
              };
              break;
          }
          this.setData({ order: newItem });
          //如果当前浏览用户为自己，则不显示接单按钮
          if (
            app.globalData.userInfo &&
            app.globalData.userInfo.openid === newItem.userInfo.openid
          ) {
            this.setData({ showAcceptButton: false });
          }
          wx.hideLoading();
        } else {
          wx.hideLoading();
          wx.showToast({ title: "服务器错误", icon: "error" });
        }
      },
      fail: (err) => {
        wx.hideLoading();
        wx.showToast({ title: "服务器错误", icon: "error" });
      },
    });
  },
  //显示订单详细信息，只有接单人员，才能查看详情
  showDetail() {
    // console.log(this.data.order);
    //读取接单人
    const { status } = this.data.order;
    if (status === "待帮助") {
      wx.showToast({ title: "接单后才可查看！", icon: "none", duration: 2000 });
    } else {
      // const _openid = app.globalData.userInfo.openid;
      if (status == "已帮助") {
        this.setData({ showDetail: !this.data.showDetail });
      } else {
        wx.showToast({
          title: "只有接单用户才可查看",
          icon: "none",
          duration: 2000,
        });
      }
    }
  },
  //调用打电话功能,给单主打电话
  call() {
    const { acceptMan } = this.data.order;
    if (!acceptMan) {
      wx.showToast({
        title: "接单后才可拨打电话！",
        icon: "none",
        duration: 2000,
      });
    } else {
      //判断当前登录用户是否为接单人员
      const _openid = app.globalData.userInfo.openid;
      if (_openid == acceptMan) {
        wx.makePhoneCall({ phoneNumber: this.data.order.userInfo.phone });
      } else {
        wx.showToast({
          title: "只有接单用户才可拨打",
          icon: "none",
          duration: 2000,
        });
      }
    }
  },
  //调用打电话功能 给接单员打电话
  callAcceptPhone() {
    //获取发单者的openid
    const { openid } = this.data.order;
    if (!openid) {
      wx.showToast({
        title: "只有发单者可拨打电话！",
        icon: "none",
        duration: 2000,
      });
    } else {
      const openidCurrent = app.globalData.userInfo.openid;
      if (openidCurrent == openid) {
        wx.makePhoneCall({ phoneNumber: this.data.acceptMan.phone });
      } else {
        wx.showToast({
          title: "只有单主用户才可拨打",
          icon: "none",
          duration: 2000,
        });
      }
    }
  },
  // 结束订单
  cancleHandle() {
    const id = this.data.completeID;
    wx.showModal({
      title: "提示",
      content: "你确定要结束订单吗？",
      success(res) {
        if (res.confirm) {
          wx.request({
            url: `${app.globalData.server}/cancleOrder`,
            data: {
              id,
              status: "待帮助",
              completed: "未完成",
              isCompleted: false,
            },
            success: (res) => {
              if (res.data === "success") {
                wx.showToast({
                  title: "操作成功",
                  success() {
                    setTimeout(() => {
                      wx.switchTab({
                        url: "/pages/order/order",
                      });
                    }, 1000);
                  },
                });
              } else {
                wx.showToast({
                  title: "操作失败",
                });
              }
            },
            fail() {
              wx.showToast({
                title: "服务器错误",
                icon: "error",
              });
            },
          });
        } else if (res.cancel) {
          wx.showToast({
            title: "用户点击取消",
            icon: "error",
          });
        }
      },
    });
  },
  //申请退款
  applyBackMoney() {
    wx.showModal({
      title: "提示",
      content: "请复制下方微信管理员微信，联系退款！",
      showCancel: false,
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},
});
